// pages/history/history.js
const util = require('../../utils/util.js');

Page({
  data: {
    activeTab: 'today', // or 'history'
    allOrders: [],
    todayOrders: [],
    historyOrders: [],
    loading: true
  },

  onShow: function () {
    this.getOrders();
  },

  // 切换Tab
  switchTab: function(e) {
    const tab = e.currentTarget.dataset.tab;
    if (tab !== this.data.activeTab) {
      this.setData({ activeTab: tab });
    }
  },

  getOrders: function() {
    this.setData({ loading: true });
    wx.cloud.callFunction({
        name: 'getOrders'
    }).then(res => {
      if (res.result && res.result.success) {
        
        // --- *** 修改：移除小程序端的数据库访问和排队计算 *** ---
        const orders = res.result.data; // (数据已在云函数中包含 queueAhead)
        const todayStr = new Date().toISOString().split('T')[0];
        const todayOrders = [];
        const historyOrders = [];

        // (移除 const db = ...)
        // (移除 const _ = ...)
        // (移除 enrichQueueAhead 函数定义)
        // (移除 Promise.all)

        // 直接处理云函数返回的、已包含排队人数的数据
        orders.forEach(order => {
          order.createTimeFormatted = util.formatTime(new Date(order.createTime));
          const orderDateStr = new Date(order.createTime).toISOString().split('T')[0];
          
          if (orderDateStr === todayStr) {
            todayOrders.push(order);
          } else {
            historyOrders.push(order);
          }
        });

        this.setData({
          allOrders: orders,
          todayOrders: todayOrders,
          historyOrders: historyOrders,
          loading: false
        });
        // --- *** 修改结束 *** ---

      } else {
        throw new Error('获取订单失败');
      }
    }).catch(err => {
      this.setData({ loading: false });
      wx.showToast({ title: '加载失败', icon: 'none' });
      console.error('获取订单列表失败', err);
    });
  },

  // 跳转到订单详情页
  goToDetail: function(e) {
    const orderId = e.detail.orderId;
    wx.navigateTo({
      url: `/pages/order-status/order-status?orderId=${orderId}`,
    });
  },
  
  // 处理“再来一单”
  handleReprint: function(e) {
    const orderInfo = e.detail.orderInfo;
    
    // 准备要传递给下一页的数据
    const reprintData = {
      printerId: orderInfo.printerId,
      fileName: orderInfo.fileName,
      filePath: null, // filePath需要用户重新选择
      fileUrl: orderInfo.fileUrl, // 保留云文件ID，方便未来扩展“直接打印”
      printOptions: orderInfo.printOptions
    };

    wx.setStorageSync('orderInfo', reprintData);

    wx.showToast({
      title: '已恢复打印设置',
      icon: 'none',
      duration: 1500,
      success: () => {
        setTimeout(() => {
          wx.navigateTo({
            // 跳转到上传页面，让用户可以确认或更换文件
            url: '/pages/upload/upload?from=reprint',
          });
        }, 1500);
      }
    });
  }
});